package com.small.nacos.core.distributed.distro.task.delay;

import com.small.nacos.common.task.AbstractDelayTask;
import com.small.nacos.core.distributed.distro.entity.DistroKey;
import com.small.nacos.naming.consistency.DataOperation;

/**
 * @Author zhoujin
 * @Date 2022/11/13 13:02
 */
public class DistroDelayTask extends AbstractDelayTask {

    /**
     * Distro任务key
     */
    private final DistroKey distroKey;

    /**
     * 数据操作动作
     */
    private DataOperation action;

    /**
     * 创建时间
     */
    private long createTime;

    public DistroDelayTask(DistroKey distroKey, long delayTime) {
        this(distroKey, DataOperation.CHANGE, delayTime);
    }
    public DistroDelayTask(DistroKey distroKey, DataOperation action, long delayTime) {
        this.distroKey = distroKey;
        this.action = action;
        this.createTime = System.currentTimeMillis();
        setLastProcessTime(createTime);
        setTaskInterval(delayTime);
    }


    @Override
    public void merge(AbstractDelayTask task) {
        if (!(task instanceof DistroDelayTask)) {
            return;
        }
        DistroDelayTask oldTask = (DistroDelayTask) task;
        // 若旧的任务和新的任务的操作类型不同，并且新任务的创建时间小于旧任务的创建时间，说明当前这个新任务还未被添加成功
        // 这个新的任务已经过时了，不需要再执行这个任务的操作，因此将旧的任务的操作类型和创建时间设置给新任务
        if (!action.equals(oldTask.getAction()) && createTime < oldTask.getCreateTime()) {
            action = oldTask.getAction();
            createTime = oldTask.getCreateTime();
        }
        //设置最后执行时间
        setLastProcessTime(oldTask.getLastProcessTime());
    }


    public DistroKey getDistroKey() {
        return distroKey;
    }

    public DataOperation getAction() {
        return action;
    }

    public long getCreateTime() {
        return createTime;
    }
}
